# Check requirements.
# Use specific version of Sphinx which fixes local search and has
# better C++ support.
find_program(DOXYGEN doxygen)
if (NOT DOXYGEN)
  message(STATUS "Target doc disabled (requires doxygen)")
  return ()
endif ()

set(BUILD_DOCS ${MP_SOURCE_DIR}/support/build-docs.py)

# Get .rst file names from amplgsl.cc.
set(amplgsl_docs )
set(amplgsl_src ${MP_SOURCE_DIR}/src/gsl/amplgsl.cc)
file(READ ${amplgsl_src} content)
string(REGEX MATCHALL "@file[^\n]*" files ${content})
foreach (f ${files})
   if (f MATCHES "@file +(.*)")
     set(amplgsl_docs ${amplgsl_docs}
         ${CMAKE_CURRENT_BINARY_DIR}/amplgsl/${CMAKE_MATCH_1}.rst)
   endif ()
endforeach ()

# Add a command to extract the amplgsl documentation from amplgsl.cc.
add_custom_command(OUTPUT ${amplgsl_docs}
  COMMAND ${BUILD_DOCS} extract-docs ${amplgsl_src}
  WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
  DEPENDS ${BUILD_DOCS} ${amplgsl_src})

# Add commands to copy .rst files to the binary directory.
# This is needed because some of the .rst files are autogenerated and
# therefore should be placed in the binary directory, while Sphinx only
# looks for source files in subdirectories of the directory containing
# the master file (index.rst).
add_prefix(docs amplgsl/
  accuracy examples fdl freedoc front-matter gpl history index intro
  no-warranty rng)
if (NOT ${CMAKE_CURRENT_SOURCE_DIR} STREQUAL ${CMAKE_CURRENT_BINARY_DIR})
  set(doc_deps ${BUILD_DOCS})
  foreach (doc ${docs} common index nl-reader)
    set(src ${CMAKE_CURRENT_SOURCE_DIR}/${doc}.rst)
    set(dst ${CMAKE_CURRENT_BINARY_DIR}/${doc}.rst)
    add_custom_command(OUTPUT ${dst}
      COMMAND ${CMAKE_COMMAND} -E copy ${src} ${dst} DEPENDS ${src})
    set(doc_deps ${doc_deps} ${dst})
  endforeach ()
endif ()
add_prefix(doc_deps ../ ${MP_HEADERS})

add_custom_target(doc
  COMMAND python ${BUILD_DOCS}
  DEPENDS conf.py ${doc_deps} ${amplgsl_docs})

install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/ampl.github.io/
        DESTINATION share/doc/mp OPTIONAL
        PATTERN .* EXCLUDE)
